// #ifndef VUE3
import Vue from 'vue'
import Vuex from 'vuex';
Vue.use(Vuex)
const store = new Vuex.Store({
// #endif

// #ifdef VUE3
import { createStore } from 'vuex'
const store = createStore({
// #endif
	state: {
		cart: []
	},
	mutations: {
		setInitCart(state, list) {
			state.cart = list;
		},
		addCart(state, goods) {
			const { id, name, pic, price } = goods;
			let targetItem = state.cart.find(item => item.id === id);
			if (targetItem) {
				targetItem.num ++;
			} else {
				let obj = {
					id,
					name,
					pic,
					price,
					num: 1,
					isChecked: false
				};
				state.cart.push(obj);
			}
			uni.setStorageSync('cart', state.cart);
		},
		// 改变购物车的数量
		changeNum(state, {id, num}) {
			let targetItem = state.cart.find(item => item.id === id);
			targetItem.num = num;
			uni.setStorageSync('cart', state.cart);
		},
		// 改变选中状态
		changeChecked(state, id) {
			let targetItem = state.cart.find(item => item.id === id);
			targetItem.isChecked = !targetItem.isChecked;
		},
		changeAllChecked(state, isChecked) {
			state.cart.forEach(item => item.isChecked = isChecked);
		},
		deleteGoods(state) {
			state.cart = state.cart.filter(item => !item.isChecked);
			uni.setStorageSync('cart', state.cart);
		},
		deleteOneGoods(state, id) {
			let index = state.cart.findIndex(item => item.id === id);
			state.cart.splice(index, 1);
			uni.setStorageSync('cart', state.cart);
		}
	},
	getters: {

	},
	actions: {

	}
})

export default store
